from sqlalchemy import func

from app.models import db
from werkzeug.security import generate_password_hash, check_password_hash


def isAvailable(account):
    Passenger.query.filter_by(account=account).first()


class Passenger(db.Model):
    __tablename__ = 'passenger'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(120))
    account = db.Column(db.String(120), unique=True, nullable=False, index=True)
    password_digest = db.Column(db.String(2000), nullable=False)
    id_card_no = db.Column(db.String(120))
    mobile_no = db.Column(db.String(120))
    bank_card_no = db.Column(db.String(120))
    state = db.Column(db.Integer, default=0)
    member_type = db.Column(db.Integer)
    last_login_time = db.Column(db.DateTime)
    created_at = db.Column(db.DateTime, default=func.now())
    updated_at = db.Column(db.DateTime, default=func.now())

    def check_password(self, password):
        return check_password_hash(self.password_digest, password)  # 验证密码

    @classmethod
    def verifyPassenger(cls, account, password):
        passenger = cls.query.filter_by(account=account).first()
        if passenger and passenger.check_password(password):
            return passenger
        return None

    @classmethod
    def create(cls, data):
        passenger = cls(
            account=data.get('account'),
            password_digest=generate_password_hash(data.get('password')),
            name=data.get('name'),
            id_card_no=data.get('idCardNo'),
            mobile_no=data.get('mobileNo'),
            bank_card_no=data.get('bankCard'),
        )
        db.session.add(passenger)
        db.session.commit()
        return passenger

    @classmethod
    def destroy(cls, passenger_id):
        passenger = cls.query.get(passenger_id)
        if passenger:
            db.session.delete(passenger)
            db.session.commit()
            return True
        return False
